import { ElMessage } from 'element-plus'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router';
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';

const router = useRouter();

interface YXRequestConfig extends AxiosRequestConfig {
  headers?: any
}

const service = axios.create({
  baseURL: '/api'
});

service.interceptors.request.use(
  (config: YXRequestConfig) => {
    // localStorage.clear()
    const token = localStorage.getItem('token')
    console.log('请求拦截token', JSON.stringify(token))
    if(token) {
      config.headers['Authorization'] = token
      console.log('www')
    }
    return config
  },
  (error: any) => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  async (response: AxiosResponse) => {
    // do something
    let code = 0;
    code = response.data.code
    console.log('response', code)
    if (code) {
      if (code == 400) {
        ElMessage.error(response.data.msg)
      }
    }
    return Promise.resolve(response.data);
  },
  (error: any) => {
    // do something
    if (error.response.data) {
      error.message = error.response.data.msg
    }
    if (error.response.status === 401) {
      router.push("/login")
    } else {
      ElNotification.error('接口请求失败');
    }
    return Promise.reject(error);
  }
)

export default service;
